package com.song.ResourceNode.server;

import com.song.ResourceNode.ResourceInit;
import com.song.ResourceNode.bean.ResourceConfig;
import com.song.ResourceNode.client.NodeClient;
import com.song.corebean.Host;
import com.song.corebean.MessageType;
import com.song.corebean.PackageHead;
import com.song.corebean.PackageMessage;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NodeServer {

	
	
	public void  start(String addr , int port ,boolean isMaster)
	{
		ResourceConfig.isMaster = isMaster;
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
				.localAddress(addr , port)
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch)
							throws Exception {
						ChannelPipeline p = ch.pipeline();
						p.addLast(new ObjectEncoder(), new ObjectDecoder(
								ClassResolvers.cacheDisabled(null)),new NodeServerHandler());
					}

				});
		try {
			ChannelFuture f = bootstrap.bind().sync();
			addhost(addr, port);
			f.channel().closeFuture().sync();

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	
	public void addhost(String addr , int port)
	{
		PackageMessage msg = new PackageMessage();
		msg.body.bundle.put("data", new Host(addr, port));
		NodeClient client = new NodeClient();
		client.connect(ResourceConfig.infoCenterAddr, ResourceConfig.infoCenterPort);
		client.sendAndRecv(MessageType.ADD_HOST,"data",new Host(addr, port));
		client.release();
		return ;
	}
	
	public static void main(String[] args) {
		ResourceInit.init();
		NodeServer server =  new NodeServer();
//		server.start("192.168.2.114",58001, true);
		server.start("192.168.2.114",58002, false);
//		server.start("192.168.2.114",58003, false);
//		server.start("192.168.2.114",58004, false);
//		server.start("192.168.2.114",58005, false);
	}
	
}
